package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @Author YWB
 * @Date 2021/1/19
 * desc 请求处理器
 **/
public class RequestProcessor extends Thread{
    private Socket socket;
    private Map<String,HttpServlet> servletMap;

    public RequestProcessor(Socket socket,Map<String,HttpServlet> servletMap){
        this.socket=socket;
        this.servletMap=servletMap;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            //封装请求返回对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            //处理静态资源
            if(servletMap.get(request.getUrl())==null){
                response.outPutHtml(request.getUrl());
            }else {
                //处理动态资源
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }
            //结束链接
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
